package com.omesoft.hksnore.util.dbhelper;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.omesoft.hksnore.util.data.MyDateUtil;
import com.omesoft.hksnore.util.entity.FamilyDTO;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DBHelperUtil extends SQLiteOpenHelper {

    private static String DB_PATH = SetData.DB_PATH;// 设置数据库的路径
    private static DBHelperUtil dbHelper;
    private static SQLiteDatabase db;

    private DBHelperUtil(Context context, int versionCode, String DB_NAME) {
        super(context, DB_NAME, null, versionCode);
        // Log.d("test", "DBHelper::versionCode::" + versionCode);
        createDataBase(this, context, DB_NAME);// 创建数据库
    }

    /**
     * 采用双重检查加锁实例化单件
     */
    public static DBHelperUtil getInstance(Context context, String DB_NAME) {
        // 双重加锁！！

        if (dbHelper == null) // 第一次检查
        {
            synchronized (DBHelperUtil.class) {
                if (dbHelper == null) // 第二次检查
                {
                    int versionCode = SoftParam.getVersionCode(context);
                    dbHelper = new DBHelperUtil(context, versionCode, DB_NAME);
                }
            }
        }
        return dbHelper;
    }

    private static void copydatabase(Context context, String dbName) {
        try {
            // 在src中得到预先保存的数据库,并于流的形式返回
//            InputStream myInput = context.getClassLoader().getResourceAsStream(dbName);
            InputStream myInput = context.getAssets().open(dbName);
            String outFileName = DB_PATH + dbName;
            // 用流的形式把数据库文件添加到指定的目录里
            OutputStream myOutput = new FileOutputStream(outFileName);
            byte[] buffer = new byte[2048];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);// 复制
            }
            myOutput.flush();
            myOutput.close();
            myInput.close();
        } catch (IOException e) {
        }
    }

    private static void createDataBase(DBHelperUtil dbHelper, Context context, String DB_NAME) {
        boolean dbExist = checkDataBase(DB_NAME);
        if (!dbExist) {// 判断手机中是否存在数据库
            copydatabase(context, DB_NAME);// 如果不存在数据库就把数据库复制到指定的路径
            db = dbHelper.getReadableDatabase();
        } else {
            if (db != null) {
                db.close();
                db = dbHelper.getReadableDatabase();
            }
        }
    }

    private static boolean checkDataBase(String DB_NAME) {

        File dir = new File(DB_PATH);
        Log.v("DBHelper::", "dir.mkdir()" + dir+"    "+"DB_NAME   "+DB_NAME);
        if (!dir.exists()) {
            dir.mkdirs(); // 如果目录中不存在，创建这个目录
        } else {
            try {

                String myPath = DB_PATH + DB_NAME;
                // 检查数据库是否存在
                Log.v("DBHelper::checkDataBase", "myPath=" + myPath);
                db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
            } catch (SQLiteException e) {
                // e.printStackTrace();

            }
        }
        return db != null ? true : false;
    }





    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }


    public static SQLiteDatabase getDb() {
        return db;
    }

    public static void setDb(SQLiteDatabase db) {
        DBHelperUtil.db = db;
    }


    public Cursor findAll(String table) {
        String sql = "select * from " + table;
        Cursor cursor = db.rawQuery(sql, null);
        return cursor;
    }

    public Cursor findAllByTime(String table) {
        String sql = "select * from " + table + " order by record_date desc";
        Cursor cursor = db.rawQuery(sql, null);
        return cursor;
    }

    public Cursor findAllSyncTime(String table, String timestamp) {
        String sql = "select * from " + table + " where created_date>='" + timestamp + "'";
        Cursor cursor = db.rawQuery(sql, null);
        return cursor;
    }

    public void deleteTable(String table) {
        String sql = "delete from " + table;
        db.execSQL(sql);
    }

    /**
     * 插入家庭成员
     *
     * @param family
     */
    public void insertFamily(FamilyDTO family) {
        db.beginTransaction();
        try {
            String recordDate = MyDateUtil.getDateFormatToString(null);
            String sql = "insert into " + SetData.TABLE_NAME_MEMBER_FAMILY + " values( '0','" + family.getFamily_id() + "','" + family.getAvatar() + "','" + family.getName()
                    + "','" + family.getGender() + "'," + family.getBirthday() + ",'" + family.getPhone() + "','"  + family.getWeight() + "','"+ family.getHeight() + "','"+family.getHipline() + "','"+family.getReal_name() + "','"+family.getDetice_mac() +"','"+family.getMember_id() +"')";
            db.execSQL(sql);
            db.setTransactionSuccessful();
            System.out.println("insertBody sql=" + sql);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
    }

    public void updateFamily(FamilyDTO family) {
        db.beginTransaction();
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(SetData.TABLE_NAME_MEMBER_FAMILY).append(" set name= '" + family.getName() + "' , avatar = '" + family.getAvatar() + "', gender = " + family.getGender() + " , birthday = '" + family.getBirthday() +  "'").append("  where family_id =").append(family.getFamily_id())
            ;
            System.out.println("updateFamily sql=" + sb.toString());
            db.execSQL(sb.toString());

            db.setTransactionSuccessful();
        } catch (Exception e) {
        } finally {
            db.endTransaction();
        }
    }
}